package cn.pomelo.ws.controller;

import cn.hutool.json.JSONUtil;
import cn.pomelo.ws.domain.entity.User;
import cn.pomelo.ws.domain.resp.Result;
import cn.pomelo.ws.service.UserService;
import cn.pomelo.ws.util.Constants;
import cn.pomelo.ws.util.JwtUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, List<Integer>> listRedisTemplate; // 存储登录用户信息

    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            return Result.failure("用户名或密码不能为空");
        }
        User login = userService.login(username, password);
        if (login == null) {
            return Result.failure("登录失败");
        }
        // 获取存储在线用户信息
        List<Integer> onlineUsers = Optional.ofNullable(listRedisTemplate.opsForValue().get(Constants.REDIS_LOGIN))
                .orElse(new ArrayList<>());
        // 如果不包含现在登录的用户就添加
        if (!onlineUsers.contains(login.getId())) {
            onlineUsers.add(login.getId());
        }
        listRedisTemplate.opsForValue().set(Constants.REDIS_LOGIN, onlineUsers);
        // 登录成功 将用户信息加密成 token 返回给前端
        String token = JwtUtils.sign(JSONUtil.toJsonStr(login));
        // 构建返回给前端的信息 token 以及 username
        Map<String, String> result = Map.of("token", token,
                "username", login.getUsername(),
                "id", String.valueOf(login.getId()),
                "avatar", login.getAvatar());
        return Result.success("登录成功", result);
    }

    @RequestMapping("/friends")
    public Result getFriends(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            return Result.failure("请先登录");
        }
        // 根据 token 解析获取登录的用户信息
        User login = JSONUtil.toBean(JwtUtils.getSubject(token), User.class);
        User user = userService.selectByPrimaryKey(login.getId());
        return user == null ? Result.failure("获取失败") : Result.success("成功", user.getFriendships());
    }
}
